<template>
  <van-dialog
    class="blog-m-dialog"
    v-if="show"
    v-model="show"
    :title="title"
    show-cancel-button
    :before-close="beforeClose"
  >
    <MBaseForm ref="formCom" :type="type" />
    <div class="blog-route--register">
    <van-button   @click="routeUser"  size="mini" plain type="info">注册</van-button>
    </div>
  </van-dialog>
</template>

<script>
import MBaseForm from "./MBaseForm";
import { Notify } from "vant";
import MODAL_DATA from '@/config/modal.config'
export default {
  name: "VueEleMuserLogin",
  components: {
    MBaseForm,
  },
  data() {
    return {
      show: false,
      type: "",
      formCom: null,
      vantFormCom: null,
    };
  },
  computed: {
    title(){
      return MODAL_DATA[this.type]?.title
    }
  },
  mounted() {
    this.$bus.$on("showUserLogin", this.showUserLogin);
  },
  beforeDestroy() {
    this.$bus.$off("showUserLogin", this.showUserLogin);
  },
  methods: {
    showUserLogin(type) {
      this.show = true;
      this.type = type;
    },
    resetForm() {
      this.formCom.form = {};
      this.vantFormCom.resetValidation();
    },
    beforeClose(action, done) {
      this.formCom = this.$refs["formCom"];
      this.vantFormCom = this.$refs["formCom"]?.$refs["blogForm"];
      if (action === "confirm") {
        let formData = this.formCom.form;
        this.vantFormCom
          .validate()
          .then(async () => {
            try {
              let result = await this.$http({
                type: this.type,
                data: formData,
              });
              console.log(result);
              Notify({
                message: `${result.message}`,
                type: "success",
              });
              done()
              //登录成功后, 关闭登录的deilog, 然后重新启动评论区内容
              this.$bus.$emit('showActionSheet')
            } catch (err) {
              // 这里的错误是请求后服务端报错
              console.log(err);
              Notify({
                message: `${err.response.data.message}`,
                type: "danger",
              });
            }
            // this.resetForm();
            done(false);
          })
          .catch((err) => {
            //这里的错误是前端验证错误
            console.log(err);
            done(false);
          });
        return false;
      }
      this.resetForm();
      done();
    },
    routeUser() {
      this.show = false
      this.$router.push({name: 'mUser', query: {state: 'register'}})
    }
  },
};
</script>
<style lang="stylus" 
>
.blog-m-dialog
  padding 0 1em
.blog-route--register
  box-sizing border-box
  display flex
  justify-content flex-end
  width 100%
  padding .25em 1em 0

</style>